<template>
		<el-card class="layout-query">
		<el-form ref="queryRef" :inline="true" :model="tableData.queryForm" @keyup.enter="queryTaskList()">
			<el-form-item prop="taskName">
			  <el-input v-model="tableData.queryForm.taskName" placeholder="作业名称"></el-input>
			</el-form-item>
			<el-form-item>
				<el-select v-model="tableData.queryForm.courseUserId" clearable placeholder="课程" style="width: 240px;">
				<el-option v-for="item in data.courseUserList" :key="item.id" :label="item.courseName" :value="item.id" />
				</el-select>
			</el-form-item>
			<el-form-item>
				<el-button icon="Search" type="primary" @click="queryTaskList()">查询</el-button>
			</el-form-item>
			<el-form-item>
				<el-button icon="RefreshRight" @click="reset(queryRef)">重置</el-button>
			</el-form-item>
		</el-form>
	</el-card>

	<el-card 
	v-loading="loading"
    :element-loading-svg="svg"
    class="custom-loading-svg"
    element-loading-svg-view-box="-10, -10, 50, 50"
	>
		<el-table v-loading="state.dataListLoading" :data="tableData.taskList" border class="layout-table" show-overflow-tooltip @selection-change="selectionChangeHandle" >
			<el-table-column type="selection" header-align="center" align="center" width="50"></el-table-column>
			<el-table-column prop="taskName" label="作业名称" header-align="center" align="center"></el-table-column>
			<el-table-column prop="startTime" label="作业开始时间" header-align="center" align="center"></el-table-column>
			<el-table-column prop="endTime" label="作业结束时间" header-align="center" align="center"></el-table-column>
			<el-table-column label="教师得分" header-align="center" align="center">
				<template #default="scope">
					<el-text type="warning">{{ scope.row.userScore || '未评' }} </el-text>
				</template>
			</el-table-column>
			<el-table-column label="大模型得分" header-align="center" align="center">
				<template #default="scope">
					<el-text type="primary">{{ scope.row.aiScore || '未评'}}</el-text>
				</template>
			</el-table-column>

			<el-table-column label="作业得分" fixed="right" header-align="center" align="center">
				<template #default="scope">
					<el-text type="success">{{ scope.row.score }}</el-text> / <el-text>{{
						scope.row.totalScore }}</el-text>
				</template>
			</el-table-column>
			<el-table-column label="状态" fixed="right" header-align="center" align="center" width="100">
				<template #default="scope">
					<el-tag :type="getStatusType(scope.row.taskState)">
						{{ getStatusLabel(scope.row.taskState) }}
					</el-tag>
				</template>
			</el-table-column>
			<el-table-column label="操作" fixed="right" header-align="center" align="center" width="300">
				<template #default="scope">
					<el-button type="primary" link @click="goToCreateTask(scope.row.taskId)">查看作业</el-button>
					<el-button v-if="scope.row.taskState === '4'" type="primary" link @click="goToCreateEventTask(scope.row.taskId)">创建评估成果任务</el-button>
				</template>
			</el-table-column>
		</el-table>
		<!-- <el-pagination
			:current-page="state.page"
			:page-sizes="state.pageSizes"
			:page-size="state.limit"
			:total="state.total"
			layout="total, sizes, prev, pager, next, jumper"
			@size-change="sizeChangeHandle"
			@current-change="currentChangeHandle"
		>
		</el-pagination> -->

		<!-- 弹窗, 新增 / 修改 -->
		<!-- <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdateRef" v-model:visible="addOrUpdateVisible" @refreshDataList="getDataList"></add-or-update> -->
	</el-card>
</template>

<script setup lang="ts" name="SmTaskIndex">
	import {useCrud} from '@/hooks'
	import {reactive, nextTick, ref,onMounted} from 'vue'
	import {IHooksOptions} from '@/hooks/interface'
	import { useRoute, useRouter } from 'vue-router';
	import { stuCourseList} from '@/api/smstu/course'
	import {saveEventTask} from '@/api/smstu/task'
	import { ElMessage } from 'element-plus'
	import { getDataStuList } from '@/api/smstu/task';
  	const route = useRoute();
	const router = useRouter();
  	const courseUserId = route.query.courseUserId;
	const state: IHooksOptions = reactive({
	
})
const tableData  = ref({
	queryForm: {
		courseUserId: courseUserId,
		taskName: ''
	},
	taskList:[]
})
const loading = ref(false)
const svg = `
        <path class="path" d="
          M 30 15
          L 28 17
          M 25.61 25.61
          A 15 15, 0, 0, 1, 15 30
          A 15 15, 0, 1, 1, 27.99 7.5
          L 15 15
        " style="stroke-width: 4px; fill: rgba(0, 0, 0, 0)"/>
      `
// 状态类型配置
const statusConfig: Record<string, { label: string; type: string }> = {
	'0': { label: '未开始', type: 'warning' },
	'1': { label: '未完成', type: 'danger' },
	'2': { label: '已保存', type: 'info' },
	'3': { label: '已评估', type: 'primary' },
	'4': { label: '已完成', type: 'success' },
	'5': { label: '已总结', type: 'primary' },
}
onMounted(async () => {
  console.log("开始初始化页面...");
  try {
    const isSuccess = await queryCourseList();
    
    if (isSuccess) {
      await queryTaskList();
      console.log("数据列表加载完成");
    }
  } catch (error) {
    console.error("初始化错误:", error);
  }
});
const queryTaskList = async () => {
	console.log("查询参数",tableData.value.queryForm);
	await getDataStuList(tableData.value.queryForm).then((res) => {
		tableData.value.taskList = res.data
	})
}
// 班级课程列表
const data = ref({
	courseUserList: [
		{
			id: 1,
			courseName: '计算机网络'
		}
	]
})

// 查询班级课程列表（返回 Promise）
const queryCourseList = async () => {
  try {
    const response = await stuCourseList();
    data.value.courseUserList = response.data;
    
    // ✅ 确保数组非空再设置默认值
    if (data.value.courseUserList.length > 0) {
      tableData.value.queryForm.courseUserId = data.value.courseUserList[0].id;
    } else {
      ElMessage.warning('无可用课程，请先创建班级');
      tableData.value.queryForm.courseUserId = null;
    }
    
    console.log("课程列表加载完成，当前 courseUserId:", tableData.value.queryForm.courseUserId);
    return true; // 返回成功状态
  } catch (error) {
    ElMessage.error('课程加载失败');
    return false;
  }
};
const queryRef = ref()
const addOrUpdateVisible = ref(false)
const addOrUpdateRef = ref()
// 跳转创建作业页面
const goToCreateTask = (taskId?: string) => {
    router.push({
        path: '/smstu/task/taskDetail',
        query: {
			taskId,
			courseUserId
        }
    });
};
// 创建评估任务页面
const goToCreateEventTask = (taskId : string) => {
	loading.value = true
	saveEventTask(taskId).then(() => {
		ElMessage.success('创建评估任务成功')
		queryTaskList()
	}).finally(() => {
		loading.value = false
	})
};
// 获取状态类型（直接通过状态码访问）
const getStatusType = (status: string | number) => {
	const key = String(status) // 确保类型一致
	return statusConfig[key]?.type || 'info' // 默认值
}

// 获取状态文本（直接通过状态码访问）
const getStatusLabel = (status: string | number) => {
	const key = String(status)
	return statusConfig[key]?.label || '未知状态' // 默认值
}
const {selectionChangeHandle, sizeChangeHandle, currentChangeHandle, reset } = useCrud(state)
</script>
